package me.zhengjie.modules.weixin.callback;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import me.zhengjie.constant.ConstantUtils;
import me.zhengjie.modules.system.domain.CourseClassStudent;
import me.zhengjie.modules.system.domain.CourseMealsOrder;
import me.zhengjie.modules.system.service.CourseClassStudentService;
import me.zhengjie.modules.system.service.CourseMealsOrderService;
import me.zhengjie.modules.system.service.dto.CourseClassStudentDto;
import me.zhengjie.modules.system.service.dto.CourseClassStudentQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.CourseClassStudentExpMapper;
import me.zhengjie.utils.DateUtil;
import me.zhengjie.utils.enums.OrderPrefixEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;

@Service
public class MealsCallbackServiceImpl implements IPayCallbackService{
    private static final Logger log = LoggerFactory.getLogger(MealsCallbackServiceImpl.class);
    @Autowired
    private CourseMealsOrderService orderService;

    @Autowired
    private CourseClassStudentExpMapper courseClassStudentExpMapper;

    @Override
    public OrderPrefixEnum prefix() {
        return OrderPrefixEnum.Meals;
    }

    @Override
    public boolean execute(WxPayOrderNotifyResult notifyResult) {
        CourseMealsOrder one = orderService.findOne(notifyResult.getOutTradeNo());
        if (one.getMeals().multiply(BigDecimal.valueOf(100)).compareTo(BigDecimal.valueOf(notifyResult.getTotalFee())) != 0){
            log.error("支付金额和订单金额不一致");
            return false;
        }
        one.setPayAmount(new BigDecimal(notifyResult.getTotalFee()).divide(new BigDecimal(100)));
        one.setPaySerialid(notifyResult.getTransactionId());
        one.setPayStatus(ConstantUtils.Order_Payed);
        one.setOrderStatus(ConstantUtils.Order_Payed);
        one.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        orderService.update(one);

        CourseClassStudent student = new CourseClassStudent();
        student.setMealsStatus(ConstantUtils.Meals_Payed);
        student.setUpdateTime(DateUtil.TimestampNow());
        LambdaQueryWrapper<CourseClassStudent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseClassStudent::getClassNo,one.getClassNo()).eq(CourseClassStudent::getOpenId,one.getOpenId());
        courseClassStudentExpMapper.update(student,wrapper);


        return true;
    }
}